//
//  WBTextView.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/16.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

class WBTextView: UITextView {
    /// 占位文本的属性
    var placeHolder: String = "请输入文本..." {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont? {
        didSet {
            placeHolderLabel.font = font
        }
    }
    
    /// 显示占位文本的label
    fileprivate lazy var placeHolderLabel: UILabel = UILabel(text: self.placeHolder, textColor: UIColor.lightGray)
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        //在初始化时，设置一个默认的font,会调用font的didSet方法，给placeHolderLable的font属性赋值
        self.font = UIFont.systemFont(ofSize: 18)
        
        //接收textView的文本变化的通知
        let notification = UITextView.textDidChangeNotification
        NotificationCenter.default.addObserver(self, selector: #selector(textChange), name: notification, object: nil)
        
        //在垂直方向添加回弹效果
        alwaysBounceVertical = true
        //拉动时隐藏键盘
        keyboardDismissMode = .onDrag
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension WBTextView {
    func setupUI () {
        addSubview(placeHolderLabel)
        
        placeHolderLabel.snp.makeConstraints { (make) in
            make.left.equalTo(5)
            make.top.equalTo(8)
            make.right.equalTo(-5)
        }
    }
}

extension WBTextView {
    @objc func textChange() {
        //print(#function)
        placeHolderLabel.isHidden = self.text.count > 0
    }
}

// MARK: - 让textView能够处理表情键盘数据
extension WBTextView {
    func insertEmotion(emotion: WBEmotionModel) {
        //代表是emoji表情
        if emotion.type == 1 {
            let emoji = NSString.emoji(withStringCode: emotion.code!)
            insertText(emoji!)
        } else {
            //代表是图片表情
            //1. 使用图片，创建一个附件（专门在富文本收使用的）
            let attachment = NSTextAttachment()
            attachment.image = UIImage(named: emotion.fullPath!)
            //bounds这个属性可以设置图片的大小
            attachment.bounds = CGRect(x: 0, y: -3, width: self.font!.lineHeight, height: self.font!.lineHeight)
            
            //2. 使用这个图片附件，创建一个图片富文本
            let imageAttStr = NSAttributedString(attachment: attachment)
            let mutableImageAttStr = NSMutableAttributedString(attributedString: imageAttStr)
            
            //给图片的富文本添加样式
            mutableImageAttStr.addAttributes([NSAttributedString.Key.font: self.font!], range: NSMakeRange(0, mutableImageAttStr.length))
            
            //3. 拿到textView的文本
            let attributtedText = self.attributedText.copy() as! NSAttributedString
            //生成一个可变的富文本
            let mutableAttStr = NSMutableAttributedString(attributedString: attributtedText)
            
            //将图片的富文本拼在textView的富文本的后面
            //append：只能把参数字符串拼在最后面；insert：只能插入不能替换；replace：可以插入，也可以替换
            //mutableAttStr.insert(mutableImageAttStr, at: range.location)
            //mutableAttStr.append(mutableImageAttStr)
            //取到光标（选中区）
            var range = self.selectedRange
            mutableAttStr.replaceCharacters(in: range, with: mutableImageAttStr)
            //把光标移动到插入的表情字符的后面
            range.location += 1
            //不选中任何字符
            range.length = 0

            self.attributedText = mutableAttStr
            //重新设置selectedRange属性
            self.selectedRange = range
        }
        
        //手动发通知
        let notificationzName = UITextView.textDidChangeNotification
        let notification = Notification.init(name: notificationzName)
        NotificationCenter.default.post(notification)
        
        //手动调代理
        delegate?.textViewDidChange!(self)
    }
}


